package com.whfc.quality.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whfc.base.param.AppFileExportParam;
import com.whfc.base.service.AppExportService;
import com.whfc.common.exception.BizException;
import com.whfc.common.file.FileHandler;
import com.whfc.common.file.FilePathConfig;
import com.whfc.common.file.properties.FileExpirationRules;
import com.whfc.common.result.PageData;
import com.whfc.common.result.PageVO;
import com.whfc.common.result.PageVOUtil;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.*;
import com.whfc.entity.param.check.CheckSearchParam;
import com.whfc.fuum.service.SysDeptService;
import com.whfc.quality.dao.*;
import com.whfc.quality.dto.*;
import com.whfc.quality.entity.QualityTask;
import com.whfc.quality.entity.QualityTaskItem;
import com.whfc.quality.entity.QualityTaskItemExec;
import com.whfc.quality.entity.QualityTaskItemTime;
import com.whfc.quality.enums.*;
import com.whfc.quality.param.*;
import com.whfc.quality.service.QualityTaskService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @ClasssName QualityTaskServiceImpl
 * @Description 检查任务服务类
 * @Author hw
 * @Date 2021/3/5 10:06
 * @Version 1.0
 */
@DubboService(interfaceClass = QualityTaskService.class, version = "1.0.0", timeout = 5000)
public class QualityTaskServiceImpl implements QualityTaskService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private QualityTaskMapper qualityTaskMapper;

    @Autowired
    private QualityTaskItemMapper qualityTaskItemMapper;

    @Autowired
    private QualityTaskItemPartMapper qualityTaskItemPartMapper;

    @Autowired
    private QualityTaskItemTimeMapper qualityTaskItemTimeMapper;

    @Autowired
    private QualityTaskItemExecMapper qualityTaskItemExecMapper;

    @Autowired
    private QualityTaskItemImgMapper qualityTaskItemImgMapper;


    @DubboReference(interfaceClass = SysDeptService.class, version = "1.0.0")
    private SysDeptService sysDeptService;

    @DubboReference(interfaceClass = AppExportService.class, version = "1.0.0")
    private AppExportService appExportService;

    @Autowired
    private FilePathConfig msFilePathConfig;

    @Autowired
    private FileHandler fileHandler;

    private final static String EXPORT_IMG_TEMPLATE = "<img src='%s' />";

    private final static String QUALITY_FILE_DESC = "质量巡查问题导出";

    private final static String HTML_TEMPLATE_PATH = "pdfTemp/qualityTaskTemp.html";

    private JSONObject pdfConfig;

    private final static String PDF_CONFIG_PATH = "pdfConfig/config.json";

    @PostConstruct
    public void info() throws IOException {
        ClassPathResource resource = new ClassPathResource(PDF_CONFIG_PATH);
        InputStream templateFileInputStream = resource.getInputStream();
        String pdfConfigStr = new String(FileUtil.readData(templateFileInputStream));
        if (StringUtils.isNotEmpty(pdfConfigStr)) {
            pdfConfig = JSONObject.parseObject(pdfConfigStr);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void taskAdd(QualityTaskAddParam param) {
        logger.info("添加检查任务,param:{}", param);
        QualityTask qualityTask = new QualityTask();
        qualityTask.setDeptId(param.getDeptId());
        qualityTask.setTitle(param.getTitle());
        qualityTask.setContent(param.getContent());
        qualityTask.setCreateUserId(param.getCreateUserId());
        qualityTask.setCreateUserName(param.getCreateUserName());
        qualityTaskMapper.insertSelective(qualityTask);
        List<QualityTaskAddListParam> taskList = param.getTaskList();
        saveItem(qualityTask.getId(), taskList);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void taskEdit(QualityTaskEditParam param) {
        logger.info("修改检查任务,param:{}", JSONObject.toJSONString(param));
        QualityTask qualityTask = qualityTaskMapper.selectByPrimaryKey(param.getTaskId());
        if (qualityTask == null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "检查任务不存在");
        }
        if (!TaskState.unpublished.getValue().equals(qualityTask.getState())) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "检查任务已发布不可修改");
        }
        qualityTask.setTitle(param.getTitle());
        qualityTask.setContent(param.getContent());
        qualityTask.setUpdateUserId(param.getUpdateUserId());
        qualityTask.setUpdateUserName(param.getUpdateUserName());
        qualityTaskMapper.updateByPrimaryKeySelective(qualityTask);
        //删除对应任务
        qualityTaskItemMapper.del(qualityTask.getId());
        qualityTaskItemTimeMapper.del(qualityTask.getId());
        qualityTaskItemPartMapper.del(qualityTask.getId());
        List<QualityTaskAddListParam> taskList = param.getTaskList();
        saveItem(qualityTask.getId(), taskList);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delTask(Integer taskId) throws BizException {
        logger.info("删除检查任务，taskId:{}", taskId);
        QualityTask qualityTask = qualityTaskMapper.selectByPrimaryKey(taskId);
        if (qualityTask == null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "检查任务不存在");
        }
        if (!TaskState.unpublished.getValue().equals(qualityTask.getState())) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "检查任务已发布不可删除");
        }
        qualityTask.setDelFlag(1);
        qualityTaskItemMapper.del(qualityTask.getId());
        qualityTaskItemTimeMapper.del(qualityTask.getId());
        qualityTaskItemPartMapper.del(qualityTask.getId());
        qualityTaskMapper.updateByPrimaryKeySelective(qualityTask);
    }

    @Override
    public PageData<QualityTaskDTO> taskList(Integer deptId, String title, Integer overdue, Integer state,
                                             Date startTime, Date endTime, Integer pageNum, Integer pageSize) throws BizException {
        logger.info("检查任务列表,deptId:{},title:{},overdue:{},state:{},startTime:{},endTime:{},pageNum:{},pageSize:{}",
                deptId, title, overdue, state, startTime, endTime, pageNum, pageSize);
        if (startTime != null || endTime != null) {
            startTime = DateUtil.getDateBegin(startTime);
            endTime = DateUtil.getDateEnd(endTime);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<QualityTaskDTO> list = qualityTaskMapper.selectByDeptId(deptId, title, overdue, state, startTime, endTime);
        PageHelper.clearPage();
        return PageUtil.pageData(PageInfo.of(list));
    }


    @Override
    public QualityExecNumDTO taskNum(Integer deptId, String title, Integer overdue, Date startTime, Date endTime) throws BizException {
        logger.info("检查任务统计,deptId:{},title：{}，overdue：{}，startTime:{},endTime:{}",
                deptId, title, overdue, startTime, endTime);
        if (startTime != null || endTime != null) {
            startTime = DateUtil.getDateBegin(startTime);
            endTime = DateUtil.getDateEnd(endTime);
        }
        return qualityTaskMapper.selectNumByDeptId(deptId, title, overdue, startTime, endTime);
    }

    @Override
    public List<QualityTaskDetailsDTO> taskDetails(Integer taskId) throws BizException {
        logger.info("检查任务详情（不分页）,taskId:{}", taskId);
        List<QualityTaskDetailsDTO> list = qualityTaskItemMapper.selectDetailsByTaskId(taskId);
        getTaskDetails(list);
        return list;
    }

    @Override
    public PageData<QualityTaskDetailsDTO> taskDetails(Integer taskId, Integer pageNum, Integer pageSize) throws BizException {
        logger.info("检查任务详情（分页）,taskId:{}，pageNum：{}，pageSize：{}", taskId, pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<QualityTaskDetailsDTO> list = qualityTaskItemMapper.selectDetailsByTaskId(taskId);
        PageHelper.clearPage();
        getTaskDetails(list);
        return PageUtil.pageData(PageInfo.of(list));
    }

    @Override
    public PageData<QualityExecDetailsDTO> execDetailsList(Integer taskItemId, Integer pageNum, Integer pageSize) throws BizException {
        logger.info("检查信息详情,taskItemId:{}，pageNum：{}，pageSize：{}", taskItemId, pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<QualityExecDetailsDTO> list = qualityTaskItemExecMapper.selectDetailsByTaskItemId(taskItemId);
        PageHelper.clearPage();
        list.forEach(qualityTaskExecDTO -> {
            List<String> imgUrls = qualityTaskItemImgMapper.selectImgUrlByExecId(qualityTaskExecDTO.getExecId());
            qualityTaskExecDTO.setImgUrls(imgUrls);
        });
        return PageUtil.pageData(PageInfo.of(list));
    }

    @Override
    public QualityExecNumDTO execNum(Integer taskItemId) throws BizException {
        logger.info("检查信息数据,taskItemId:{}", taskItemId);
        return qualityTaskItemExecMapper.selectExecNumByTaskItemId(taskItemId);
    }


    @Override
    public PageData<QualityTaskExecDTO> taskExecList(Integer userId, Integer deptId,
                                                     String keyword, Integer overdue,
                                                     Integer partId, Integer state,
                                                     Date startTime, Date endTime,
                                                     Integer pageNum, Integer pageSize) throws BizException {
        logger.info("我的任务,userId:{},deptId:{},keyword:{},overdue:{},partId:{},state:{},startTime:{},endTime:{},pageNum:{},pageSize:{}",
                userId, deptId, keyword, overdue, partId, state, startTime, endTime, pageNum, pageSize);
        if (startTime != null || endTime != null) {
            startTime = DateUtil.getDateBegin(startTime);
            endTime = DateUtil.getDateEnd(endTime);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<QualityTaskExecDTO> list = qualityTaskItemExecMapper.selectByDeptId(userId, deptId, keyword, overdue, partId, state, startTime, endTime);
        PageHelper.clearPage();
        list.forEach(qualityTaskExecDTO -> {
            List<String> imgUrls = qualityTaskItemImgMapper.selectImgUrlByExecId(qualityTaskExecDTO.getExecId());
            qualityTaskExecDTO.setImgUrls(imgUrls);
        });
        return PageUtil.pageData(PageInfo.of(list));
    }

    @Override
    public List<QualityTaskExecDTO> taskExecList(Integer userId, Integer deptId, String keyword, Integer overdue, Integer state, Date startTime, Date endTime) throws BizException {
        logger.info("我的任务列表,userId:{},deptId:{},keyword:{},overdue:{},state:{},startTime:{},endTime:{}", userId, deptId, keyword, overdue, state, startTime, endTime);
        if (startTime != null || endTime != null) {
            startTime = DateUtil.getDateBegin(startTime);
            endTime = DateUtil.getDateEnd(endTime);
        }
        List<QualityTaskExecDTO> list = qualityTaskItemExecMapper.selectByDeptId(userId, deptId, keyword, overdue, null, state, startTime, endTime);
        list.forEach(qualityTaskExecDTO -> {
            List<String> imgUrls = qualityTaskItemImgMapper.selectImgUrlByExecId(qualityTaskExecDTO.getExecId());
            qualityTaskExecDTO.setImgUrls(imgUrls);
        });
        return list;
    }

    @Override
    public PageData<QualityTaskExecDTO> taskExecList(Integer deptId, Integer partId,
                                                     Date startTime, Date endTime,
                                                     Integer pageNum, Integer pageSize) throws BizException {
        logger.info("检查记录列表（分页）,deptId:{},partId:{},startTime:{},endTime:{},pageNum:{},pageSize:{}",
                deptId, partId, startTime, endTime, pageNum, pageSize);
        if (startTime != null || endTime != null) {
            startTime = DateUtil.getDateBegin(startTime);
            endTime = DateUtil.getDateEnd(endTime);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<QualityTaskExecDTO> list = qualityTaskItemExecMapper.selectByDeptIdAndUserId(null, deptId, partId, 2, startTime, endTime);
        PageHelper.clearPage();
        list.forEach(qualityTaskExecDTO -> {
            List<String> imgUrls = qualityTaskItemImgMapper.selectImgUrlByExecId(qualityTaskExecDTO.getExecId());
            qualityTaskExecDTO.setImgUrls(imgUrls);
        });
        return PageUtil.pageData(PageInfo.of(list));
    }

    @Override
    public List<QualityTaskExecDTO> taskExecList(Integer deptId, Integer partId,
                                                 Date startTime, Date endTime) throws BizException {
        logger.info("检查记录列表（不分页）,deptId：{},partId：{},startTime：{},endTime：{}", deptId, partId, startTime, endTime);
        if (startTime != null || endTime != null) {
            startTime = DateUtil.getDateBegin(startTime);
            endTime = DateUtil.getDateEnd(endTime);
        }
        List<QualityTaskExecDTO> list = qualityTaskItemExecMapper.selectByDeptIdAndUserId(null, deptId, partId, 2, startTime, endTime);
        list.forEach(qualityTaskExecDTO -> {
            List<String> imgUrls = qualityTaskItemImgMapper.selectImgUrlByExecId(qualityTaskExecDTO.getExecId());
            qualityTaskExecDTO.setImgUrls(imgUrls);
        });
        return list;
    }

    @Override
    public PageData<QualityTaskExecDTO> taskExecList(Integer userId, Integer deptId, Integer partId, Date startTime, Date endTime, Integer pageNum, Integer pageSize) throws BizException {
        logger.info("检查记录列表（分页）,userId:{},deptId:{},partId:{},startTime:{},endTime:{},pageNum:{},pageSize:{}",
                userId, deptId, partId, startTime, endTime, pageNum, pageSize);
        if (startTime != null || endTime != null) {
            startTime = DateUtil.getDateBegin(startTime);
            endTime = DateUtil.getDateEnd(endTime);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<QualityTaskExecDTO> list = qualityTaskItemExecMapper.selectByDeptIdAndUserId(userId, deptId, partId, 2, startTime, endTime);
        PageHelper.clearPage();
        list.forEach(qualityTaskExecDTO -> {
            List<String> imgUrls = qualityTaskItemImgMapper.selectImgUrlByExecId(qualityTaskExecDTO.getExecId());
            qualityTaskExecDTO.setImgUrls(imgUrls);
        });
        return PageUtil.pageData(PageInfo.of(list));
    }

    @Override
    public List<QualityTaskExecDTO> taskExecList(Integer userId, Integer deptId, Integer partId, Date startTime, Date endTime) throws BizException {
        logger.info("检查记录列表（不分页）,userId:{},deptId：{},partId：{},startTime：{},endTime：{}", userId, deptId, partId, startTime, endTime);
        if (startTime != null || endTime != null) {
            startTime = DateUtil.getDateBegin(startTime);
            endTime = DateUtil.getDateEnd(endTime);
        }
        List<QualityTaskExecDTO> list = qualityTaskItemExecMapper.selectByDeptIdAndUserId(userId, deptId, partId, 2, startTime, endTime);
        list.forEach(qualityTaskExecDTO -> {
            List<String> imgUrls = qualityTaskItemImgMapper.selectImgUrlByExecId(qualityTaskExecDTO.getExecId());
            qualityTaskExecDTO.setImgUrls(imgUrls);
        });
        return list;
    }

    @Override
    public void execDel(Integer execId) throws BizException {
        qualityTaskItemExecMapper.logicDel(execId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void report(QualityTaskReportParam param) {
        logger.info("排查上报,param：{}", param);
        QualityTaskItemExec exec = new QualityTaskItemExec();
        exec.setDeptId(param.getDeptId());
        exec.setLat(param.getLat());
        exec.setLng(param.getLng());
        exec.setLocation(param.getLocation());
        if (param.getPartId() == null) {
            param.setPartId(-1);
        }
        exec.setPartId(param.getPartId());
        exec.setPartName(param.getPartName());
        exec.setCheckUserId(param.getUserId());
        exec.setCheckUserName(param.getUserName());
        exec.setCheckTime(new Date());
        exec.setOverdue(OverdueStatus.NOT_OVERDUE.getValue());
        exec.setCheckResult(param.getCheckResult());
        exec.setTaskType(TaskType.report.getValue());
        exec.setState(TaskItemState.done.getValue());
        qualityTaskItemExecMapper.insertSelective(exec);
        List<String> imgUrls = param.getImgUrls();
        if (imgUrls != null && imgUrls.size() > 0) {
            qualityTaskItemImgMapper.insertAll(exec.getId(), imgUrls);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void taskRelease(QualityTaskReleaseParam param) {
        logger.info("发布,param:{}", JSONObject.toJSONString(param));
        QualityTask qualityTask = qualityTaskMapper.selectByPrimaryKey(param.getTaskId());
        if (qualityTask == null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "检查任务不存在");
        }
        qualityTask.setPublishUserId(param.getUserId());
        qualityTask.setPublishUserName(param.getUserName());
        qualityTask.setPublishTime(new Date());
        qualityTask.setUpdateUserId(param.getUserId());
        qualityTask.setUpdateUserName(param.getUserName());
        qualityTask.setState(TaskState.unstarted.getValue());
        List<QualityTaskItem> items = qualityTaskItemMapper.selectByTaskId(param.getTaskId());
        items.forEach(taskItem -> {
            List<QualityTaskItemPartDTO> itemParts = qualityTaskItemPartMapper.selectByTaskItemId(taskItem.getId());
            List<QualityTaskItemTime> itemTimes = qualityTaskItemTimeMapper.selectByTaskItemId(taskItem.getId());
            qualityTaskItemExecMapper.insertAll(qualityTask.getDeptId(), qualityTask.getId(), taskItem, itemParts, itemTimes);
        });
        qualityTaskMapper.updateByPrimaryKeySelective(qualityTask);

        List<QualityTaskItemExec> execs = qualityTaskItemExecMapper.selectByTaskId(param.getTaskId());
        if (execs == null || execs.isEmpty()) {
            return;
        }
        List<Integer> execIds = execs.stream().map(QualityTaskItemExec::getId).distinct().collect(Collectors.toList());
        List<Integer> taskIds = execs.stream().map(QualityTaskItemExec::getTaskId).distinct().collect(Collectors.toList());
        List<Integer> taskItemIds = execs.stream().map(QualityTaskItemExec::getTaskItemId).distinct().collect(Collectors.toList());
        qualityTaskItemExecMapper.updateStateByExecIds(execIds);
        qualityTaskMapper.updateStateByTaskIds(taskIds);
        qualityTaskItemMapper.updateStateByTaskItem(taskItemIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void complete(QuailTaskCompleteParam param) throws BizException {
        logger.info("完成任务,param:{}", JSONObject.toJSONString(param));
        QualityTaskItemExec exec = qualityTaskItemExecMapper.selectByPrimaryKey(param.getExecId());
        if (exec == null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "检查任务不存在");
        }
        exec.setLat(param.getLat());
        exec.setLng(param.getLng());
        exec.setLocation(param.getLocation());
        exec.setCheckUserId(param.getUserId());
        exec.setCheckUserName(param.getUserName());
        exec.setCheckTime(new Date());
        exec.setCheckResult(param.getCheckResult());
        exec.setState(TaskItemState.done.getValue());
        qualityTaskItemExecMapper.updateByPrimaryKeySelective(exec);

        Integer taskItemId = exec.getTaskItemId();
        Integer taskId = exec.getTaskId();

        QualityTaskItem item = qualityTaskItemMapper.selectByPrimaryKey(taskItemId);
        String[] progress = item.getProgress().split("/");
        Integer completeNum = Integer.valueOf(progress[0]);
        completeNum++;
        item.setProgress(completeNum + "/" + progress[1]);
        qualityTaskItemMapper.updateByPrimaryKeySelective(item);

        List<QualityTaskItemExec> execs = qualityTaskItemExecMapper.selectUnfinishedByTaskItemId(taskItemId);
        if (execs == null || execs.isEmpty()) {
            item.setState(TaskItemState.done.getValue());
            qualityTaskItemMapper.updateByPrimaryKeySelective(item);
        }

        execs = qualityTaskItemExecMapper.selectUnfinishedByTaskId(taskId);
        if (execs == null || execs.isEmpty()) {
            QualityTask qualityTask = qualityTaskMapper.selectByPrimaryKey(taskId);
            qualityTask.setState(TaskState.done.getValue());
            qualityTaskMapper.updateByPrimaryKeySelective(qualityTask);
        }
        List<String> imgs = param.getImgUrls();
        if (imgs != null && imgs.size() > 0) {
            qualityTaskItemImgMapper.insertAll(exec.getId(), imgs);
        }
    }


    @Override
    public QualityExecNumDTO execNum(Integer userId, Integer deptId, String keyword, Integer overdue, Date startTime, Date endTime) throws BizException {
        logger.info("我的任务,userId:{},deptId:{},keyword:{},overdue:{},startTime:{},endTime:{}",
                userId, deptId, keyword, overdue, startTime, endTime);
        if (startTime != null || endTime != null) {
            startTime = DateUtil.getDateBegin(startTime);
            endTime = DateUtil.getDateEnd(endTime);
        }
        return qualityTaskItemExecMapper.selectExecNumByDeptId(userId, deptId, keyword, overdue, startTime, endTime);
    }


    @Override
    public QualityExecNumDTO execNum(Integer userId, Integer deptId, Integer partId, Date startTime, Date endTime) throws BizException {
        logger.info("检查记录统计,deptId:{},userId:{},partId:{},startTime:{},endTime:{}",
                deptId, userId, partId, startTime, endTime);
        startTime = DateUtil.getDateBegin(startTime);
        endTime = DateUtil.getDateEnd(endTime);
        return qualityTaskItemExecMapper.selectMeNum(userId, deptId, partId, startTime, endTime);
    }

    @Override
    public void excExport(List<Integer> execIds, Integer deptId) throws BizException {
        String fileDesc = QUALITY_FILE_DESC;
        String fileName = RandomUtil.getRandomFileName();
        String suffix = execIds.size() > 1 ? "zip" : "pdf";
        AppFileExportParam fileExport = new AppFileExportParam();
        fileExport.setDeptId(deptId);
        fileExport.setFileName(fileName);
        fileExport.setFileFormat(suffix.toUpperCase());
        fileExport.setFileState(0);
        fileExport.setFileDesc(fileDesc);
        Integer id = appExportService.install(fileExport);
        fileExport.setId(id);
        AppFileExportParam upFileExport = fileExport;
        CompletableFuture.supplyAsync(() -> {
            List<InputStream> iss = new ArrayList<>();
            String footer = null;
            String header = null;
            if (pdfConfig.containsKey(deptId.toString())) {
                JSONObject config = pdfConfig.getJSONObject(deptId.toString());
                footer = config.getString("footer");
                header = config.getString("header");
            }
            for (Integer execId : execIds) {
                QualityTaskItemExec exec = qualityTaskItemExecMapper.selectByPrimaryKey(execId);
                String deptName = sysDeptService.getDeptNameById(exec.getDeptId());
                JSONObject data = new JSONObject();
                data.put("deptName", deptName);
                data.put("checkUserName", exec.getCheckUserName());
                data.put("checkTime", DateUtil.formatDate(exec.getCheckTime(), DateUtil.DATE_TIME_FORMAT));
                data.put("partName", exec.getPartName());
                data.put("checkResult", exec.getCheckResult());

                List<String> imgUrls = qualityTaskItemImgMapper.selectImgUrlByExecId(execId);
                StringBuffer imgList = new StringBuffer();
                imgUrls.forEach(s -> {
                    imgList.append(String.format(EXPORT_IMG_TEMPLATE, s));
                });
                data.put("imgList", imgList.toString());
                ClassPathResource resource = new ClassPathResource(HTML_TEMPLATE_PATH);
                String html = null;
                try {
                    InputStream templateFileInputStream = resource.getInputStream();
                    File tempFile = FileUtil.copyTemplateFile(templateFileInputStream);
                    html = HtmlUtil.freeMarkerRender(data, tempFile);
                    ByteArrayOutputStream arrayOutputStream = ItextPdfUtil.htmlToPdf(html, header, footer);
                    iss.add(new ByteArrayInputStream(arrayOutputStream.toByteArray()));
                } catch (IOException e) {
                    logger.error("质量pdf导出异常", e);
                }
            }
            InputStream is = null;
            if (suffix.equals("zip")) {
                try {
                    is = ZipUtil.zipPdfFile(iss);
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error("压缩文件失败", e);
                }
            } else {
                is = iss.get(0);
            }
            String path = msFilePathConfig.getFilePath("quality/export", fileName, suffix);
            String upload = fileHandler.upload(path, is, FileExpirationRules.DAYS_1);
            upFileExport.setFileUrl(upload);
            upFileExport.setFileState(1);
            appExportService.update(upFileExport);
            return null;
        });
    }

    @Override
    public PageVO<QualityTaskExecDTO> getTaskPage(CheckSearchParam param) {
        PageVOUtil.startPage(param);
        List<QualityTaskExecDTO> list = qualityTaskItemExecMapper.selectTaskExecPage(param);
        PageVOUtil.clearPage();
        list.forEach(qualityTaskExecDTO -> {
            List<String> imgUrls = qualityTaskItemImgMapper.selectImgUrlByExecId(qualityTaskExecDTO.getExecId());
            qualityTaskExecDTO.setImgUrls(imgUrls);
        });
        return PageVOUtil.page(PageInfo.of(list));
    }

    /**
     * 保存检查任务项
     *
     * @param taskId
     * @param taskList
     */
    private void saveItem(Integer taskId, List<QualityTaskAddListParam> taskList) {
        taskList.forEach(taskParam -> {
            QualityTaskItem item = new QualityTaskItem();
            item.setTaskId(taskId);
            item.setCheckUserId(taskParam.getUserId());
            item.setCheckUserName(taskParam.getUserName());
            item.setCheckType(taskParam.getCheckType());
            List<Date> timeList = taskParam.getTimeList();
            List<Integer> partIdList = taskParam.getPartIdList();
            item.setProgress(getProgress(taskParam.getCheckType(), partIdList, timeList));
            qualityTaskItemMapper.insertSelective(item);
            savePartAndTime(taskId, item.getId(), taskParam);
        });
    }


    /**
     * 保存部位和时间
     *
     * @param taskId
     * @param itemId
     * @param param
     */
    private void savePartAndTime(Integer taskId, Integer itemId, QualityTaskAddListParam param) {
        List<Date> timeList = param.getTimeList();
        timeList.sort(Comparator.naturalOrder());
        if (CheckType.dailyCheck.getValue().equals(param.getCheckType())) {
            List<QualityTaskItemTime> mapList = new ArrayList<>();
            timeList.forEach(date -> {
                QualityTaskItemTime time = new QualityTaskItemTime();
                time.setStartDate(DateUtil.getDateBegin(date));
                time.setEndDate(DateUtil.getDateEnd(date));
                mapList.add(time);
            });
            qualityTaskItemTimeMapper.insertAll(taskId, itemId, mapList);
        } else if (CheckType.singleCheck.getValue().equals(param.getCheckType())) {
            QualityTaskItemTime time = new QualityTaskItemTime();
            time.setTaskId(taskId);
            time.setTaskItemId(itemId);
            time.setStartDate(DateUtil.getDateBegin(param.getTimeList().get(0)));
            time.setEndDate(DateUtil.getDateEnd(param.getTimeList().get(1)));
            qualityTaskItemTimeMapper.insertSelective(time);
        }
        qualityTaskItemPartMapper.insertAll(taskId, itemId, param.getPartIdList());
    }

    /**
     * 获取进度
     *
     * @param checkType
     * @param partIdList
     * @param timeList
     * @return
     */
    private String getProgress(Integer checkType, List<Integer> partIdList, List<Date> timeList) {
        Integer taskAllNum = 0;
        if (CheckType.dailyCheck.getValue().equals(checkType)) {
            taskAllNum = timeList.size() * partIdList.size();
        } else if (CheckType.singleCheck.getValue().equals(checkType)) {
            taskAllNum = partIdList.size();
        }
        return "0/" + taskAllNum;
    }

    /**
     * 获取检查任务详情
     *
     * @param list
     */
    private void getTaskDetails(List<QualityTaskDetailsDTO> list) {
        list.forEach(qualityTaskDetailsDTO -> {
            List<QualityTaskItemPartDTO> partList = qualityTaskItemPartMapper.selectByTaskItemId(qualityTaskDetailsDTO.getTaskItemId());
            List<QualityTaskItemTime> timeList = qualityTaskItemTimeMapper.selectByTaskItemId(qualityTaskDetailsDTO.getTaskItemId());
            List<Date> times = new ArrayList<>();
            if (CheckType.singleCheck.getValue().equals(qualityTaskDetailsDTO.getCheckType())) {
                QualityTaskItemTime time = timeList.get(0);
                times.add(time.getStartDate());
                times.add(time.getEndDate());
            } else {
                times = timeList.stream().map(QualityTaskItemTime::getStartDate).collect(Collectors.toList());
            }
            qualityTaskDetailsDTO.setTimes(times);
            qualityTaskDetailsDTO.setPartList(partList);
        });
    }
}
